/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-09-16
 * Time: 13:01
 */
public class test4 {
    // 最终数字
    private static final int FINAL_NUMBER = 200;
    // 锁
    private static Object lock = new Object();
    // 当前数字
    private static int currentNum = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (currentNum < FINAL_NUMBER) {  // 修改循环条件为<=
                synchronized (lock) {
                    // 双重检查：先检查是否超过目标值，再检查是否是自己该打印的数字
                    while (currentNum <= FINAL_NUMBER && currentNum % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    // 再次检查，确保不打印超过FINAL_NUMBER的数字
                    if (currentNum > FINAL_NUMBER) {
                        lock.notifyAll();  // 唤醒其他线程，让它们也能退出
                        break;
                    }
                    System.out.println("t1:" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (currentNum < FINAL_NUMBER) {  // 修改循环条件为<=
                synchronized (lock) {
                    while (currentNum <= FINAL_NUMBER && currentNum % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if (currentNum > FINAL_NUMBER) {
                        lock.notifyAll();
                        break;
                    }
                    System.out.println("t2:" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });

        Thread t3 = new Thread(() -> {
            while (currentNum < FINAL_NUMBER) {  // 修改循环条件为<=
                synchronized (lock) {
                    while (currentNum <= FINAL_NUMBER && currentNum % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if (currentNum > FINAL_NUMBER) {
                        lock.notifyAll();
                        break;
                    }
                    System.out.println("t3:" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
